var express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const { OutfitModel,Conversation,KnowledgeBase } = require('../db/index');
const axios = require('axios');
const fs = require('fs');
const path = require('path');

// Dify API配置
const DIFY_API_KEY = process.env.DIFY_API_KEY || 'app-TAsYfN7a82mIhEdaaLozWLm2';
const DIFY_API_ENDPOINT = process.env.DIFY_API_ENDPOINT || 'http://localhost:5001/v1';

// 配置
const PYTHON_SERVICE_URL = process.env.PYTHON_SERVICE_URL || 'http://localhost:8000';
const OUTFIT_IMAGES_DIR = path.join(__dirname, '../py_service/outfit_images');
const PY_SERVICE_PATH = path.join(__dirname, '../py_service');

// 确保目录存在
if (!fs.existsSync(OUTFIT_IMAGES_DIR)){
  try {
    fs.mkdirSync(OUTFIT_IMAGES_DIR, { recursive: true });
    console.log(`创建穿搭图片目录: ${OUTFIT_IMAGES_DIR}`);
  } catch (err) {
    console.error(`无法创建穿搭图片目录: ${err.message}`);
  }
}

// 生成今日穿搭
async function generateOutfit() {
  try {
    // 调用Dify API生成穿搭建议
    const response = await axios.post(`${DIFY_API_ENDPOINT}/chat-messages`, {
      query: '请根据今天的天气和场合，推荐一套适合的穿搭',
      response_mode: 'blocking',
      conversation_id: 'outfit-generation'
    }, {
      headers: {
        'Authorization': `Bearer ${DIFY_API_KEY}`,
        'Content-Type': 'application/json'
      }
    });

    // 解析Dify返回的穿搭建议
    const outfitDescription = response.data.answer;
    
    // 使用AI生成图片URL (这里需要替换为实际的图片生成API)
    const imageUrl = 'https://example.com/generated-outfit.jpg';

    // 保存到数据库
    const today = new Date().toISOString().slice(0, 10);
    const outfit = await OutfitModel.create({
      date: today,
      image_url: imageUrl,
      description: outfitDescription
    });

    return outfit;
  } catch (error) {
    console.error('生成穿搭失败:', error);
    throw error;
  }
}

// 调用Dify工作流函数
async function callDifyWorkflow(prompt, workflowId, conversationId) {
  try {
    const response = await axios.post(`${DIFY_API_ENDPOINT}/chat-messages`, {
      query: prompt,
      response_mode: 'blocking',
      conversation_id: conversationId || `workflow-${workflowId}`,
      workflow_id: workflowId
    }, {
      headers: {
        'Authorization': `Bearer ${DIFY_API_KEY}`,
        'Content-Type': 'application/json'
      }
    });
    
    return response.data;
  } catch (error) {
    console.error('调用Dify工作流失败:', error);
    throw error;
  }
}

// 生成高质量上下文对话
async function generateQualityConversation(context, workflowId) {
  try {
    const prompt = `基于以下上下文，生成一个高质量的问答对：\n\n${context}`;
    const response = await callDifyWorkflow(prompt, workflowId);
    
    if (response && response.answer) {
      // 解析返回的问答对
      const result = JSON.parse(response.answer);
      return {
        question: result.question,
        answer: result.answer,
        context: context,
        quality_score: result.quality_score || 0.8,
        dify_workflow_id: workflowId
      };
    }
    
    throw new Error('无法从Dify工作流中获取有效回复');
  } catch (error) {
    console.error('生成高质量对话失败:', error);
    throw error;
  }
}

// 确保模型已注册
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 写入一条对话
router.post('/conversation', async function(req, res, next) {
  try {
    const data = req.body; // {userId, user_input, ai_reply, ...}
    const result = await Conversation.create(data);
    res.json({ success: true, id: result._id });
  } catch (err) {
    next(err);
  }
});

// 批量写入多条对话
router.post('/conversations', async function(req, res, next) {
  try {
    const { conversations } = req.body; // [{...}, {...}]
    if (!Array.isArray(conversations)) {
      return res.status(400).json({ error: 'conversations must be an array' });
    }
    const result = await Conversation.insertMany(conversations);
    res.json({ success: true, inserted: result.length });
  } catch (err) {
    next(err);
  }
});

// 写入一条知识库问答
router.post('/knowledge', async function(req, res, next) {
  try {
    const data = req.body; // {question, answer, ...}
    const result = await KnowledgeBase.create(data);
    res.json({ success: true, id: result._id });
  } catch (err) {
    next(err);
  }
});

// 批量写入知识库
router.post('/knowledges', async function(req, res, next) {
  try {
    const { knowledge } = req.body; // [{...}, {...}]
    if (!Array.isArray(knowledge)) {
      return res.status(400).json({ error: 'knowledge must be an array' });
    }
    const result = await KnowledgeBase.insertMany(knowledge);
    res.json({ success: true, inserted: result.length });
  } catch (err) {
    next(err);
  }
});





// 新增: 存储高质量对话到知识库
router.post('/knowledge/quality', async function(req, res, next) {
  try {
    const { conversation, user_id, tag, style_type, dify_workflow_id } = req.body;
    
    if (!conversation) {
      return res.status(400).json({ error: '对话内容必填' });
    }
    
    // 使用Dify工作流生成高质量问答对
    const workflowId = dify_workflow_id || process.env.DIFY_QA_WORKFLOW_ID;
    if (!workflowId) {
      return res.status(400).json({ error: '工作流ID必填' });
    }
    
    const qaData = await generateQualityConversation(conversation, workflowId);
    
    // 添加用户信息和标签
    qaData.user_id = user_id;
    qaData.tag = tag;
    qaData.style_type = style_type;
    
    // 保存到知识库
    const result = await KnowledgeBase.create(qaData);
    res.json({ 
      success: true, 
      id: result._id,
      question: result.question,
      answer: result.answer,
      quality_score: result.quality_score 
    });
    
  } catch (err) {
    console.error('存储高质量对话失败:', err);
    res.status(500).json({ error: '存储高质量对话失败: ' + err.message });
  }
});

// 新增: 根据上下文检索相关知识
router.post('/knowledge/search', async function(req, res, next) {
  try {
    const { query, limit = 5, tags = [], user_id, threshold = 0.7 } = req.body;
    
    if (!query || query.trim().length < 2) {
      return res.status(400).json({ error: '查询内容太短' });
    }
    
    // 构建查询条件
    let searchConditions = { $text: { $search: query } };
    
    // 如果提供了标签，添加到查询条件
    if (tags && tags.length > 0) {
      searchConditions.tag = { $in: tags };
    }
    
    // 如果提供了用户ID，限制到该用户的知识
    if (user_id) {
      searchConditions.user_id = user_id;
    }
    
    // 执行查询
    const results = await KnowledgeBase.find(searchConditions)
      .sort({ score: { $meta: "textScore" }, quality_score: -1 })
      .limit(parseInt(limit));
    
    // 筛选高于阈值的结果
    const filteredResults = results.filter(item => {
      // 这里应该有一个实际的相关性分数计算
      // 暂时使用quality_score代替
      return item.quality_score >= threshold;
    });
    
    res.json({
      results: filteredResults,
      total: filteredResults.length
    });
    
  } catch (err) {
    console.error('知识库搜索失败:', err);
    res.status(500).json({ error: '知识库搜索失败: ' + err.message });
  }
});

// 新增: 在Dify工作流中使用知识库数据
router.post('/dify/workflow/with-knowledge', async function(req, res, next) {
  try {
    const { prompt, workflow_id, conversation_id, user_id } = req.body;
    
    if (!prompt || !workflow_id) {
      return res.status(400).json({ error: 'prompt和workflow_id必填' });
    }
    
    // 先从知识库中检索相关内容
    const searchResults = await KnowledgeBase.find(
      { $text: { $search: prompt }, user_id: user_id },
      { score: { $meta: "textScore" } }
    )
    .sort({ score: { $meta: "textScore" }, quality_score: -1 })
    .limit(3);
    
    // 提取知识库内容
    const knowledgeContext = searchResults.map(item => 
      `问题: ${item.question}\n回答: ${item.answer}`
    ).join('\n\n');
    
    // 构建增强的提示词
    const enhancedPrompt = knowledgeContext 
      ? `以下是一些相关的知识:\n\n${knowledgeContext}\n\n根据以上信息，请回答: ${prompt}`
      : prompt;
    
    // 调用Dify工作流
    const response = await callDifyWorkflow(enhancedPrompt, workflow_id, conversation_id);
    
    // 更新被引用的知识条目
    for (const item of searchResults) {
      await KnowledgeBase.updateOne(
        { _id: item._id },
        { $inc: { reference_count: 1 } }
      );
    }
    
    res.json({
      answer: response.answer,
      knowledge_used: searchResults.length,
      workflow_id
    });
    
  } catch (err) {
    console.error('带知识库的工作流调用失败:', err);
    res.status(500).json({ error: '调用失败: ' + err.message });
  }
});

// 新增: 从对话历史生成知识库内容
router.post('/knowledge/generate-from-history', async function(req, res, next) {
  try {
    const { user_id, limit = 20, dify_workflow_id, tag } = req.body;
    
    if (!user_id) {
      return res.status(400).json({ error: '用户ID必填' });
    }
    
    // 获取用户最近的对话
    const conversations = await Conversation.find({ userId: user_id })
      .sort({ created_at: -1 })
      .limit(parseInt(limit));
      
    if (conversations.length === 0) {
      return res.status(404).json({ error: '未找到对话历史' });
    }
    
    const workflowId = dify_workflow_id || process.env.DIFY_QA_WORKFLOW_ID;
    if (!workflowId) {
      return res.status(400).json({ error: '工作流ID必填' });
    }
    
    // 处理每个对话，生成知识库内容
    const results = [];
    for (const conv of conversations) {
      try {
        // 构建上下文
        const context = `用户问题: ${conv.user_input}\n助手回答: ${conv.ai_reply}`;
        
        // 生成高质量QA
        const qaData = await generateQualityConversation(context, workflowId);
        qaData.user_id = user_id;
        qaData.tag = tag || conv.tag || '自动生成';
        qaData.style_type = conv.style_type;
        qaData.conversation_id = conv._id.toString();
        
        // 保存到知识库
        const result = await KnowledgeBase.create(qaData);
        results.push({
          id: result._id,
          question: result.question,
          answer: result.answer,
          quality_score: result.quality_score
        });
      } catch (err) {
        console.error(`处理对话ID ${conv._id} 失败:`, err);
        // 继续处理下一个对话
      }
    }
    
    res.json({
      success: true,
      generated: results.length,
      results: results
    });
    
  } catch (err) {
    console.error('从历史生成知识失败:', err);
    res.status(500).json({ error: '从历史生成知识失败: ' + err.message });
  }
});

// 新增：代理到Python虚拟恋人API
router.all('/companion/*', async function(req, res, next) {
  try {
    const subPath = req.path.replace('/companion', '');
    const url = `${PYTHON_SERVICE_URL}${subPath}`;
    const method = req.method.toLowerCase();
    
    console.log(`[Python代理] ${method.toUpperCase()} ${url}`);
    
    let response;
    if (method === 'get') {
      response = await axios.get(url, { 
        params: req.query,
        timeout: 10000
      });
    } else if (method === 'post') {
      response = await axios.post(url, req.body, {
        timeout: 10000
      });
    } else if (method === 'put') {
      response = await axios.put(url, req.body);
    } else if (method === 'delete') {
      response = await axios.delete(url, { params: req.query });
    } else {
      return res.status(405).json({ error: "Method not allowed" });
    }
    
    res.status(response.status).json(response.data);
  } catch (error) {
    console.error(`[Python代理错误] ${req.method} ${req.path}:`, error.message);
    
    if (error.response) {
      // 如果Python服务返回错误响应
      res.status(error.response.status).json(error.response.data || { error: error.message });
    } else if (error.code === 'ECONNREFUSED' || error.code === 'ETIMEDOUT') {
      // 连接被拒绝或超时，可能是Python服务未运行
      res.status(503).json({ 
        error: "Python服务暂不可用，请确保服务已启动",
        code: error.code,
        message: "连接Python服务失败" 
      });
    } else {
      // 其他错误
      res.status(500).json({ 
        error: "内部服务器错误", 
        message: error.message,
        path: req.path
      });
    }
  }
});

// 新增: 直接代理到Python服务的所有API - 改为更具体的路径
router.all('/api/*', async function(req, res, next) {
  try {
    // 不包含已处理的路径
    if (req.path.startsWith('/companion/')) {
      return next();
    }
    
    const subPath = req.path.replace('/api', '');
    const url = `${PYTHON_SERVICE_URL}${subPath}`;
    const method = req.method.toLowerCase();
    
    console.log(`[Python代理] ${method.toUpperCase()} ${url}`);
    
    let response;
    if (method === 'get') {
      response = await axios.get(url, { 
        params: req.query,
        timeout: 10000
      });
    } else if (method === 'post') {
      response = await axios.post(url, req.body, {
        timeout: 10000
      });
    } else if (method === 'put') {
      response = await axios.put(url, req.body);
    } else if (method === 'delete') {
      response = await axios.delete(url, { params: req.query });
    } else {
      return res.status(405).json({ error: "Method not allowed" });
    }
    
    res.status(response.status).json(response.data);
  } catch (error) {
    console.error(`[Python代理错误] ${req.method} ${req.path}:`, error.message);
    
    if (error.response) {
      res.status(error.response.status).json(error.response.data || { error: error.message });
    } else if (error.code === 'ECONNREFUSED' || error.code === 'ETIMEDOUT') {
      res.status(503).json({ 
        error: "Python服务暂不可用，请确保服务已启动",
        code: error.code,
        message: "连接Python服务失败" 
      });
    } else {
      res.status(500).json({ 
        error: "内部服务器错误", 
        message: error.message,
        path: req.path
      });
    }
  }
});

module.exports = router;
